/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {boolean}
 */
var isBalanced = function(root) {

  function computeDepth(node, depth) {
    if(!node) return 0;
    if(!node.left && !node.right) return depth;
    let leftDepth = computeDepth(node.left, depth + 1), rightDepth = computeDepth(node.right, depth + 1);
    return Math.max(leftDepth, rightDepth);
  }

  let flag = true;
  function preView(node) {
    if(!node || !flag) return;
    let left = computeDepth(node.left, 1), right = computeDepth(node.right, 1);
    if(Math.abs(left - right) > 1) {
      flag = false;
    }
    preView(node.left);
    preView(node.right);
  }
  preView(root);
  return flag;
};
